﻿using MVVMLightDemo.interfaces;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace MVVMLightDemo.Implements
{
    public class ExcelService : IExcelHelper
    {
        private string _path;

        public string Path
        {
            get { return _path; }
        }

        public bool CreateExcel(string path)
        {
            using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate))
            {
                _path = path;
                if (File.Exists(path))
                {
                    return true;
                }
                return false;
            }
        }

        public bool Export<T>(List<T> data)
        {
            XSSFWorkbook wk = new XSSFWorkbook();
            ISheet tb = wk.CreateSheet("Export");
            IRow row = tb.CreateRow(0);

            //填充表头
            PropertyInfo[] propertys = data[0].GetType().GetProperties();
            for(int index = 0; index < propertys.Count(); index++)
            {
                ICell cell = row.CreateCell(index);
                cell.SetCellValue(propertys[index].Name);
            }

            //填充数据
            for (int index = 0; index < data.Count; index++)
            {
                IRow row_s = tb.CreateRow(index + 1);
                for (int index_s = 0; index_s < propertys.Count(); index_s++)
                {
                    ICell cell = row_s.CreateCell(index_s);
                    var result = propertys[index_s].GetValue(data[index], null).ToString();
                    cell.SetCellValue(result);
                }
            }

            using (FileStream stm = File.OpenWrite(_path))
            {
                wk.Write(stm);
                return true;
            }
        }
    }
}
